package design_pattern.singleton;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * 懒汉式，提供一个静态的共有方法，使用该方法时，去创建instance，创建后下一次调用不用创建直接拿到
 * 线程不安全，初始阶段有两个线程进入if条件中，就会生成两个instance
 */
public class SingletonTest3 {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
        for (int i = 0; i < 10; i++) {
            new Thread(new ThreadA(cyclicBarrier)).start();
        }

        Singleton3 instance1 = Singleton3.getInstance();
        Singleton3 instance2 = Singleton3.getInstance();
        System.out.println(instance1 == instance2);
    }


}
class ThreadA implements Runnable{
    private CyclicBarrier cyclicBarrier;

    public ThreadA(CyclicBarrier countDownLatch) {
        this.cyclicBarrier = countDownLatch;
    }

    @Override
    public void run() {
        try {
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        Singleton3 instance = Singleton3.getInstance();
        System.out.println(instance);
    }
}

class Singleton3{
    private static Singleton3 instance;
    private Singleton3(){}

    // 静态的公有方法，当使用到该方法时，才去创建 instance
    public static Singleton3 getInstance(){
        if(instance == null) instance = new Singleton3();
        return instance;
    }
}
